<template>
  <div class="my-input-wrapper">
    <div class="input-box">
      <input
        :id="mId"
        :type="type"
        :value="value"
        @input="handleInput"
        @blur="handleBlur"
        :placeholder="placeholder"
      />
    </div>
    <p class="err-msg" v-if="error">{{error}}</p>
  </div>
</template>

<script>
export default {
  name: "my-input",
  // 接收myFormItem传递的数据
  inject: ["mode"],
  data() {
    return {
      error: "",
      timer: null
    };
  },
  props: {
    placeholder: {
      type: String,
      default: ""
    },
    value: {
      type: String,
      default: ""
    },
    mId: {
      type: Number
    },
    type: {
      type: String,
      default: "text"
    }
  },
  computed: {
    rules() {
      this.mode.forEach(ele => {
        window.console.log(ele.mode);
      });
      return true;
    }
  },
  methods: {
    shake(fun, time) {
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        fun();
      }, time);
    },
    handleInput(e) {
      let inputVal = e.target.value;
      this.$emit("input", inputVal);
    },
    // input后检测数据
    checkInput() {
      this.mode.forEach((ele, index) => {
        ele.mode === "input" && this.$parent.$emit("validate", index);
      });
    },
    // blur后检测数据
    handleBlur() {
      this.mode.forEach((ele, index) => {
        ele.mode === "blur" && this.$parent.$emit("validate", index);
      });
    }
  },
  watch: {
    value() {
      this.shake(this.checkInput, 500)
    }
  }
};
</script>

<style scoped>
.my-input-wrapper {
  position: relative;
  flex: 7;
  display: flex;
  flex-direction: column;
}
.my-input-wrapper .input-box {
  display: flex;
  align-items: center;
}
.my-input-wrapper input {
  outline: none;
  width: 100%;
  height: 0.6rem;
  line-height: 0.6rem;
  box-sizing: border-box;
  border: 2px solid #dedede;
  border-radius: 4px;
  font-size: 0.32rem;
  padding: 0 0.2rem;
  flex: 5;
}
.my-input-wrapper input:focus {
  border: 2px solid deepskyblue;
}
</style>
